package lihua.robot.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Component
public class ImprovedPollerUtil {
    private static final Logger logger = LoggerFactory.getLogger(ImprovedPollerUtil.class);
    private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(3);
    private static final Set<String> terminalStates = new HashSet<>(Arrays.asList("FINISHED", "FAILED", "STOPPED", "Error"));

    public static void pollOrderStatus(String orderId, int maxAttempts, long delayMillis, String mapKey) {
        final Runnable poller = () -> {
            // attempt来跟踪尝试次数，以及getOrderDetails和RedisUtil的实现。
            int attempt = 0;
            if (attempt < maxAttempts) {
                attempt++;
                try {
                    String orderState = PostManUtil.getOrderDetails(orderId); // 假设这是从某处获取订单状态的方法
                    logger.info("Attempt #{}: Order state is {}", attempt + 1, orderState);
                    if (terminalStates.contains(orderState)) {
                        logger.info("Order processing completed with state: {}", orderState);
                        RedisUtil.setKW0(mapKey); // 更新Redis中状态的方法
                        scheduler.shutdownNow(); // 停止调度任务
                    } else {
                        logger.info("Order is still being processed. Waiting for next attempt...");
                    }
                } catch (Exception e) {
                    logger.error("Error while polling order status", e);
                }
            } else {
                logger.info("Max attempts reached. Stopping poller.");
                scheduler.shutdownNow(); // 停止调度任务
            }
        };

        scheduler.scheduleWithFixedDelay(poller, 0, delayMillis, TimeUnit.MILLISECONDS);
    }

    private static int getAndIncrementAttemptForOrder(String orderId) {
        return 0;
    }
}
